package com.example.lombokdemo.utils;

import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class AddTextToImgUtil {
    public static void main(String[] args) {
        String filePath = "E:\\文档\\仁弥科技\\盗铃空间\\盗龄记录\\1.jpg";
        String outPath = "E:\\文档\\仁弥科技\\盗铃空间\\盗龄记录\\2.jpg";   //第一次加字
        String word2 = "E:\\文档\\仁弥科技\\盗铃空间\\盗龄记录\\3.jpg";

        String webFilePath_word3 = "E:\\文档\\仁弥科技\\盗铃空间\\盗龄记录\\4.jpg";

        drawTextInImg(filePath, "阿尔法蛋AI故事机-用爸爸妈妈的声音讲故事", outPath, 60, 755, "black", 24.0f);//在图片上加商品标题（简介）
        drawTextInImg(outPath, "¥3199", word2, 90, 870, "red", 45.0f);//在图片上加商品价格
        drawTextInImg(word2, "原价：3399", webFilePath_word3, 225, 865, "black", 20.0f);//在图片上加商品原价
        System.out.println("Hello World!");
    }
    public static void drawTextInImg(String filePath, String text, String outPath,int left_n, int top_n,String color,float fsize) {
        ImageIcon imgIcon = new ImageIcon(filePath);
        Image img = imgIcon.getImage();
        int width = img.getWidth(null);
        int height = img.getHeight(null);
        BufferedImage bimage = new BufferedImage(width, height,
                BufferedImage.TYPE_INT_RGB);

        Graphics2D g = bimage.createGraphics();

        int fontSize = (int)fsize;    //字体大小
        int rectX = left_n;
        int rectY = top_n;
        int rectWidth = text.length() * (fontSize + 30);
        int rectHeight = fontSize + 8;

        Font font = new Font("宋体",Font.BOLD, fontSize);   //定义字体
        g.setBackground(Color.white);
        g.drawImage(img, 0, 0, null);
        if("black".equals(color)){
            g.setPaint(Color.black);
        }else if("red".equals(color)){
            g.setPaint(Color.red);
        }
        g.setFont(font);
        //g.drawRect(left_n, top_n, rectWidth, rectHeight);
        g.drawString(text, rectX, top_n);
        g.dispose();

        try {
            FileOutputStream out = new FileOutputStream(outPath);
            ImageIO.write(bimage, "png", out);
            out.close();
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }



}